package com.sls.web.manager.action.game;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.sls.web.manager.action.SuperAction;
import com.sls.web.manager.common.Constants;
import com.sls.web.manager.execption.ManagerException;
import com.sls.web.manager.game.pojo.maxshu.MaxshuAccountType;
import com.sls.web.manager.game.pojo.maxshu.MaxshuAreaServer;
import com.sls.web.manager.game.pojo.maxshu.MaxshuProduct;
import com.sls.web.manager.game.pojo.maxshu.MaxshuRechargeType;
import com.sls.web.manager.game.pojo.maxshu.MaxshuRespInfo;
import com.sls.web.manager.game.service.MaxshuService;
import com.sls.web.manager.page.Pagination;

@Results(value = { @Result(name = "filedownload", type = "stream", params = {
		"contentType", "application/x-download", "inputName", "istream",
		"contentDisposition", "attachment;filename=${fileName}" }) })
@InterceptorRefs({
		@InterceptorRef(value = "defaultStack", params = { "maximumSize",
				"2048000", "allowedTypes",
				"text/plain,application/excel,application/vnd.ms-excel" }),
		@InterceptorRef(value = "defalutStackSet") })
public class MaxshuAction extends SuperAction {

	private static final long serialVersionUID = 4523430272778003349L;
	@Resource(name = "maxshuService")
	private MaxshuService maxshuService;

	private Pagination<?> page;
	private MaxshuProduct proQuery;
	private MaxshuProduct proInfo;
	private MaxshuAccountType accQuery;
	private MaxshuRechargeType rechQuery;
	private MaxshuAreaServer asQuery;
	private MaxshuRespInfo respInfo;
	private String merchantId;
	private String orderId;
	private String id;
	private String productId;
	private String productName;
	private String supplierId;
	private int priceRatio;
	private String fileName;// 文件名称
	private InputStream istream; // 输入流
	private File productExcel;// 获取上传文件
	private String productExcelFileName;// 获取上传文件名称

	public String productList() throws Exception {
		if (proQuery == null) {
			proQuery = new MaxshuProduct();
			proQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
			proQuery.setPageSize(Constants.INIT_PAGESIZE);
		}
		try {
			page = this.maxshuService.queryProPagination(proQuery,
					getCurrentOperator());
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return "product_list";
	}

	public String toEditPro() throws Exception {
		try {
			proInfo = this.maxshuService.queryById(id, getCurrentOperator());
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return INPUT;
	}

	public String editPro() throws Exception {
		try {
			this.maxshuService.updatePro(proInfo, getCurrentOperator());

			if (proQuery == null) {
				proQuery = new MaxshuProduct();
				proQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
				proQuery.setPageSize(Constants.INIT_PAGESIZE);
			}
			if (StringUtils.isNotEmpty(productId)) {
				proQuery.setProductId(productId);
			}
			if (StringUtils.isNotEmpty(productName)) {
				proQuery.setProductName(productName);
			}

		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return productList();
	}

	public String sync() {
		try {
			this.maxshuService.sync(getCurrentOperator());
			this.redirectionUrl = "maxshu!productList.htm";
		} catch (ManagerException e) {
			flag = false;
			this.addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	public String accList() throws Exception {
		if (accQuery == null) {
			accQuery = new MaxshuAccountType();
			accQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
			accQuery.setPageSize(Constants.INIT_PAGESIZE);
		}
		try {
			page = this.maxshuService.queryAccPagination(accQuery,
					getCurrentOperator());
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return "acc_list";
	}

	public String rechList() throws Exception {
		if (rechQuery == null) {
			rechQuery = new MaxshuRechargeType();
			rechQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
			rechQuery.setPageSize(Constants.INIT_PAGESIZE);
		}
		try {
			page = this.maxshuService.queryRechPagination(rechQuery,
					getCurrentOperator());
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return "rech_list";
	}

	public String asList() throws Exception {
		if (asQuery == null) {
			asQuery = new MaxshuAreaServer();
			asQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
			asQuery.setPageSize(Constants.INIT_PAGESIZE);
		}
		try {
			page = this.maxshuService.queryASPagination(asQuery,
					getCurrentOperator());
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return "as_list";
	}

	public String toQueryBalance() {
		return "balance";
	}

	public String queryBalance() {
		try {
			respInfo = this.maxshuService.queryBalance(getCurrentOperator());
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return "balance";
	}

	public String toQueryOrder() {
		return "order";
	}

	public String queryOrder() {
		try {
			respInfo = this.maxshuService.queryOrder(orderId,
					getCurrentOperator());
			respInfo.setOrderId(orderId);
			respInfo.setMerchantId(merchantId);
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return "order";
	}

	public String audit() {

		try {
			this.maxshuService.confirmAudit(supplierId, priceRatio,
					getCurrentOperator());
			redirectionUrl = "maxshu!productList.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;

	}

	/**
	 * 批量上架
	 * 
	 * @return
	 * @throws Exception
	 */
	public String batchOnline() throws Exception {
		try {
			this.maxshuService.batchOnline("1", getCurrentOperator());
			redirectionUrl = "maxshu!productList.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 批量下架
	 * 
	 * @return
	 * @throws Exception
	 */
	public String batchOffline() throws Exception {
		try {
			this.maxshuService.batchOffline("0", getCurrentOperator());
			redirectionUrl = "maxshu!productList.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 导出文件
	 * 
	 * @return
	 * @throws Exception
	 */
	public String export() throws Exception {
		List<MaxshuProduct> list = null;
		try {
			list = this.maxshuService.queryAllProduct(getCurrentOperator());
		} catch (ManagerException e1) {
			addActionError(e1.getMessage());
			flag = false;
			return SUCCESS;
		}
		String filename = "数网sup产品信息.xls";
		try {
			this.createExcel(filename, list);
		} catch (IOException e) {
			addActionError("导出文件异常!");
			flag = false;
			return SUCCESS;
		}
		return "filedownload";
	}

	/**
	 * 导入产品excel文件
	 * 
	 * @return
	 * @throws Exception
	 */
	public String importProductFile() throws Exception {
		if (StringUtils.isEmpty(productExcelFileName)) {
			flag = false;
			addActionError("请选择要导入的文件!");
			return SUCCESS;
		}
		if (!productExcelFileName.endsWith(".xls")
				&& !productExcelFileName.endsWith(".xlsx")) {
			flag = false;
			addActionError("文件类型有误!<br>必须为excel文件!");
			return SUCCESS;
		}
		InputStream is = null;
		try {
			is = new FileInputStream(productExcel);
		} catch (FileNotFoundException e1) {
			addActionError(e1.getMessage());
		}
		List<MaxshuProduct> list = null;
		try {
			if (is != null) {
				if (productExcelFileName.endsWith(".xls")) {
					list = this.extractListFromXLS2003(is);
				} else if (productExcelFileName.endsWith(".xlsx")) {
					list = this.extractListFromXLS2007(is);
				}
			}
		} catch (IOException e) {
			addActionError(e.getMessage());
		}
		String message = "";
		if (list != null && !list.isEmpty()) {
			for (MaxshuProduct wo : list) {
				if (wo != null && StringUtils.isNotEmpty(wo.getProductId())) {
					try {
						this.maxshuService.save(wo, getCurrentOperator());
					} catch (ManagerException e) {
						message += wo.getProductId() + "," + e.getMessage()
								+ "<br>";
						continue;
					}
				}
			}
		}
		if (StringUtils.isNotEmpty(message)) {
			flag = false;
			addActionError(message);
		}
		this.redirectionUrl = "maxshu!productList.htm";
		return SUCCESS;
	}

	/**
	 * 创建excel表格
	 * 
	 * @param path
	 * @param list
	 * @throws IOException
	 */
	private void createExcel(String filenameWeb, List<MaxshuProduct> list)
			throws IOException {
		// 第一步，创建一个webbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet("价格信息");
		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow row = sheet.createRow(0);
		// 第四步，创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("产品编号");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("产品名称");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("产品进价(元)");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("产品面值(元)");
		cell.setCellStyle(style);

		// 第五步，写入实体数据 实际应用中这些数据从数据库得到，
		if (list != null && !list.isEmpty()) {
			for (int i = 0; i < list.size(); i++) {
				row = sheet.createRow((int) i + 1);
				MaxshuProduct wp = (MaxshuProduct) list.get(i);
				// 第四步，创建单元格，并设置值
				cell = row.createCell(0);
				cell.setCellStyle(style);
				cell.setCellValue(wp.getProductId());
				cell = row.createCell(1);
				cell.setCellStyle(style);
				cell.setCellValue(wp.getProductName());
				cell = row.createCell(2);
				cell.setCellStyle(style);
				cell.setCellValue(wp.getProductPrice());
				cell = row.createCell(3);
				cell.setCellStyle(style);
				cell.setCellValue(wp.getProductParvalue());
			}
		}

		// 第六步，将文件存到指定位置
		fileName = new String(filenameWeb.getBytes("GBK"), "iso8859-1");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		wb.write(baos);
		istream = new ByteArrayInputStream(baos.toByteArray());
		baos.close();
	}

	/**
	 * 解析excel2003文件
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	private List<MaxshuProduct> extractListFromXLS2003(InputStream is)
			throws IOException {
		List<MaxshuProduct> list = new ArrayList<MaxshuProduct>();
		MaxshuProduct wo = null;
		HSSFWorkbook workbook = new HSSFWorkbook(is); // 创建对Excel工作簿文件的引用
		for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
			if (null != workbook.getSheetAt(numSheets)) {
				HSSFSheet aSheet = workbook.getSheetAt(numSheets); // 获得一个sheet
				for (int rowNumOfSheet = 1; rowNumOfSheet <= aSheet
						.getLastRowNum(); rowNumOfSheet++) {
					if (null != aSheet.getRow(rowNumOfSheet)) {
						wo = new MaxshuProduct();
						List<String> cellList = new ArrayList<String>();
						HSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 获得一行
						for (int cellNumOfRow = 0; cellNumOfRow <= aRow
								.getLastCellNum(); cellNumOfRow++) {
							if (null != aRow.getCell(cellNumOfRow)) {
								HSSFCell aCell = aRow.getCell(cellNumOfRow); // 获得列值
								if (aCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
									double parvalue = aCell
											.getNumericCellValue();
									cellList.add(String.valueOf(parvalue));
								} else if (aCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
									boolean flag = aCell.getBooleanCellValue();
									cellList.add(String.valueOf(flag));
								} else {
									cellList.add(aCell.getStringCellValue());
								}

								if (cellList.size() > 0) {
									String proId = cellList.get(0);
									if (proId.indexOf(".") > 0) {
										proId = proId.substring(0,
												proId.indexOf("."));
									}
									wo.setProductId(proId);
								}
								if (cellList.size() > 1) {
									wo.setProductName(cellList.get(1));
								}
								if (cellList.size() > 2) {
									if ("官方直充".equals(cellList.get(2))) {
										wo.setRechargeMode("2");
									}
								}
								if (cellList.size() > 3) {
									wo.setProductParvalue(cellList.get(3));
								}
								if (cellList.size() > 4) {
									wo.setProductPrice(cellList.get(4));
								}

								if (cellList.size() > 5) {
									String remark = cellList.get(5);
									if (remark.indexOf(".") > 0) {
										remark = remark.substring(0,
												remark.indexOf("."));
									}
									wo.setRemark(remark);
								}
							}
						}

					}
					list.add(wo);
				}
			}
		}
		return list;
	}

	/**
	 * 解析excel2007文件
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	private List<MaxshuProduct> extractListFromXLS2007(InputStream is)
			throws IOException {
		List<MaxshuProduct> list = new ArrayList<MaxshuProduct>();
		MaxshuProduct wo = null;
		// 构造 XSSFWorkbook 对象，strPath
		// 传入文件路径
		XSSFWorkbook xwb = new XSSFWorkbook(is);
		// 循环工作表Sheet
		for (int numSheet = 0; numSheet < xwb.getNumberOfSheets(); numSheet++) {
			XSSFSheet xSheet = xwb.getSheetAt(numSheet);
			if (xSheet == null) {
				continue;
			}
			// 循环行Row
			for (int rowNum = 1; rowNum <= xSheet.getLastRowNum(); rowNum++) {
				wo = new MaxshuProduct();
				XSSFRow xRow = xSheet.getRow(rowNum);
				if (xRow == null) {
					continue;
				}
				List<String> cellList = new ArrayList<String>();
				// 循环列Cell
				for (int cellNum = 0; cellNum <= xRow.getLastCellNum(); cellNum++) {
					XSSFCell xCell = xRow.getCell(cellNum);

					if (xCell == null) {
						continue;
					}
					if (xCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
						boolean flag = xCell.getBooleanCellValue();
						cellList.add(String.valueOf(flag));
					} else if (xCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
						double parvalue = xCell.getNumericCellValue();
						cellList.add(String.valueOf(parvalue));
					} else {
						cellList.add(xCell.getStringCellValue());
					}
					if (cellList.size() > 0) {
						wo.setProductId(cellList.get(0));
					}
					if (cellList.size() > 1) {
						wo.setProductName(cellList.get(1));
					}
					if (cellList.size() > 2) {
						if ("官方直充".equals(cellList.get(2))) {
							wo.setRechargeMode("2");
						}
					}
					if (cellList.size() > 3) {
						wo.setProductParvalue(cellList.get(3));
					}
					if (cellList.size() > 4) {
						wo.setProductPrice(cellList.get(4));
					}

					if (cellList.size() > 5) {
						wo.setRemark(cellList.get(5));
					}
				}
				list.add(wo);
			}
		}
		return list;
	}

	public Pagination<?> getPage() {
		return page;
	}

	public void setPage(Pagination<?> page) {
		this.page = page;
	}

	public MaxshuProduct getProQuery() {
		return proQuery;
	}

	public void setProQuery(MaxshuProduct proQuery) {
		this.proQuery = proQuery;
	}

	public MaxshuAccountType getAccQuery() {
		return accQuery;
	}

	public void setAccQuery(MaxshuAccountType accQuery) {
		this.accQuery = accQuery;
	}

	public MaxshuRechargeType getRechQuery() {
		return rechQuery;
	}

	public void setRechQuery(MaxshuRechargeType rechQuery) {
		this.rechQuery = rechQuery;
	}

	public MaxshuAreaServer getAsQuery() {
		return asQuery;
	}

	public void setAsQuery(MaxshuAreaServer asQuery) {
		this.asQuery = asQuery;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getProductId() {
		return productId;
	}

	public void setProductId(String productId) {
		this.productId = productId;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public MaxshuProduct getProInfo() {
		return proInfo;
	}

	public void setProInfo(MaxshuProduct proInfo) {
		this.proInfo = proInfo;
	}

	public String getSupplierId() {
		return supplierId;
	}

	public void setSupplierId(String supplierId) {
		this.supplierId = supplierId;
	}

	public int getPriceRatio() {
		return priceRatio;
	}

	public void setPriceRatio(int priceRatio) {
		this.priceRatio = priceRatio;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public InputStream getIstream() {
		return istream;
	}

	public void setIstream(InputStream istream) {
		this.istream = istream;
	}

	public MaxshuRespInfo getRespInfo() {
		return respInfo;
	}

	public void setRespInfo(MaxshuRespInfo respInfo) {
		this.respInfo = respInfo;
	}

	public String getOrderId() {
		return orderId;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	public File getProductExcel() {
		return productExcel;
	}

	public void setProductExcel(File productExcel) {
		this.productExcel = productExcel;
	}

	public String getProductExcelFileName() {
		return productExcelFileName;
	}

	public void setProductExcelFileName(String productExcelFileName) {
		this.productExcelFileName = productExcelFileName;
	}

	public String getMerchantId() {
		return merchantId;
	}

	public void setMerchantId(String merchantId) {
		this.merchantId = merchantId;
	}

}
